package cn.hcbycloud.common.jwt.service.jwt.impl;


import cn.hcbycloud.common.core.constant.RedisDbIndex;
import cn.hcbycloud.common.core.constant.TokenExpireDayType;
import cn.hcbycloud.common.jwt.service.jwt.JwtRedisCacheService;
import cn.hcbycloud.common.jwt.vo.JwtToken;
import cn.hcbycloud.common.redis.utils.RedisOperator;
import cn.hutool.core.util.ObjectUtil;
import lombok.AllArgsConstructor;

/**
 * @author gaoh
 * @desc 实现JWTredis缓存配置
 * @date 2022年01月24日 下午 8:39
 */
@AllArgsConstructor
public class JwtRedisCacheServiceImpl implements JwtRedisCacheService {

    /**
     * redis操作服务
     */
    private RedisOperator redisOperator;

    /**
     * 返回失效天数
     *
     * @return
     */
    @Override
    public Integer getTokenExpireDays() {
        return TokenExpireDayType.TOKEN_EXPIRE_DAY_TYPE_1D_5D_DEFAULT.getTokenInCacheExpireDay();
    }

    /**
     * 将JWT令牌对象存入缓存
     *
     * @param jwtToken
     */
    @Override
    public void setTokenToCache(JwtToken jwtToken) {
        Long seconds = this.getTokenExpireDays() * 24 * 3600L;
        redisOperator.setObject(RedisDbIndex.REDIS_DB_INDEX_15.getIndex(), jwtToken.getToken(), jwtToken, seconds);
    }

    /**
     * 从缓存中获取JWT令牌对象
     *
     * @param jwtToken
     * @return
     */
    @Override
    public JwtToken getTokenFromCache(JwtToken jwtToken) {
        return (JwtToken) redisOperator.getObject(RedisDbIndex.REDIS_DB_INDEX_15.getIndex(),
                jwtToken.getToken(), JwtToken.class);
    }

    /**
     * 从缓存中删除JWT令牌对象
     *
     * @param jwtToken
     */
    @Override
    public void removeTokenFromCache(JwtToken jwtToken) {
        redisOperator.remove(RedisDbIndex.REDIS_DB_INDEX_15.getIndex(), jwtToken.getToken());
    }

    /**
     * 判断缓存中是否存在JWT令牌对象
     *
     * @param jwtToken
     * @return
     */
    @Override
    public boolean hasToken(JwtToken jwtToken) {
        return ObjectUtil.isNotNull(this.getTokenFromCache(jwtToken)) ? true : false;
    }
}